<!-- The exported code uses Tailwind CSS. Install Tailwind CSS in your dev environment to ensure all styles work. -->

<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 顶部导航栏 -->
    <Header />

    <!-- 主内容区域 -->
    <main class="pt-16">
      <div class="container mx-auto p-6">
        <!-- 面包屑导航 -->
        <div class="flex items-center text-sm mb-6 text-gray-500">
          <span>首页</span>
          <i class="fas fa-chevron-right mx-2 text-xs"></i>
          <span>监测报警</span>
          <i class="fas fa-chevron-right mx-2 text-xs"></i>
          <span class="text-blue-600">报警事件管理</span>
        </div>

        <!-- 筛选区域 -->
        <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
          <div class="grid grid-cols-4 gap-6">
            <div class="flex flex-col">
              <label class="text-sm text-gray-600 mb-2">时间范围</label>
              <div class="flex space-x-2">
                <button
                  @click="filterByTimeRange('all')"
                  :class="[
                    'px-4 py-2 text-sm rounded !rounded-button whitespace-nowrap cursor-pointer',
                    selectedTimeRange === 'all' 
                      ? 'bg-blue-600 text-white hover:bg-blue-700' 
                      : 'bg-gray-100 hover:bg-gray-200'
                  ]">全部</button>
                <button
                  @click="filterByTimeRange('today')"
                  :class="[
                    'px-4 py-2 text-sm rounded !rounded-button whitespace-nowrap cursor-pointer',
                    selectedTimeRange === 'today' 
                      ? 'bg-blue-600 text-white hover:bg-blue-700' 
                      : 'bg-gray-100 hover:bg-gray-200'
                  ]">今日</button>
                <button
                  @click="filterByTimeRange('week')"
                  :class="[
                    'px-4 py-2 text-sm rounded !rounded-button whitespace-nowrap cursor-pointer',
                    selectedTimeRange === 'week' 
                      ? 'bg-blue-600 text-white hover:bg-blue-700' 
                      : 'bg-gray-100 hover:bg-gray-200'
                  ]">本周</button>
                <button
                  @click="filterByTimeRange('month')"
                  :class="[
                    'px-4 py-2 text-sm rounded !rounded-button whitespace-nowrap cursor-pointer',
                    selectedTimeRange === 'month' 
                      ? 'bg-blue-600 text-white hover:bg-blue-700' 
                      : 'bg-gray-100 hover:bg-gray-200'
                  ]">本月</button>
              </div>
            </div>
            <div class="flex flex-col">
              <label class="text-sm text-gray-600 mb-2">报警级别</label>
              <div class="relative">
                <button
                  @click="toggleLevelDropdown"
                  class="w-full px-4 py-2 text-sm bg-white border border-gray-300 rounded flex items-center justify-between !rounded-button whitespace-nowrap cursor-pointer hover:border-blue-500 focus:outline-none focus:border-blue-500">
                  <span>{{ selectedLevel }}</span>
                  <i class="fas fa-chevron-down text-gray-400 transition-transform duration-200" :class="{ 'rotate-180': showLevelDropdown }"></i>
                </button>
                <div v-if="showLevelDropdown" class="absolute top-full left-0 right-0 mt-1 bg-white border border-gray-300 rounded shadow-lg z-10">
                  <div 
                    v-for="level in levelOptions" 
                    :key="level"
                    @click="selectLevel(level)"
                    class="px-4 py-2 text-sm hover:bg-gray-100 cursor-pointer"
                    :class="{ 'bg-blue-50 text-blue-600': selectedLevel === level }">
                    {{ level }}
                  </div>
                </div>
              </div>
            </div>
            <div class="flex flex-col">
              <label class="text-sm text-gray-600 mb-2">处理状态</label>
              <div class="relative">
                <button
                  @click="toggleStatusDropdown"
                  class="w-full px-4 py-2 text-sm bg-white border border-gray-300 rounded flex items-center justify-between !rounded-button whitespace-nowrap cursor-pointer hover:border-blue-500 focus:outline-none focus:border-blue-500">
                  <span>{{ selectedStatus }}</span>
                  <i class="fas fa-chevron-down text-gray-400 transition-transform duration-200" :class="{ 'rotate-180': showStatusDropdown }"></i>
                </button>
                <div v-if="showStatusDropdown" class="absolute top-full left-0 right-0 mt-1 bg-white border border-gray-300 rounded shadow-lg z-10">
                  <div 
                    v-for="status in statusOptions" 
                    :key="status"
                    @click="selectStatus(status)"
                    class="px-4 py-2 text-sm hover:bg-gray-100 cursor-pointer"
                    :class="{ 'bg-blue-50 text-blue-600': selectedStatus === status }">
                    {{ status }}
                  </div>
                </div>
              </div>
            </div>
            <div class="flex flex-col">
              <label class="text-sm text-gray-600 mb-2">搜索</label>
              <div class="relative">
                <input 
                  type="text" 
                  placeholder="搜索报警事件"
                  v-model="searchKeyword"
                  @input="handleSearch"
                  class="w-full px-4 py-2 text-sm border border-gray-300 rounded focus:outline-none focus:border-blue-500">
                <i class="fas fa-search absolute right-3 top-2.5 text-gray-400"></i>
              </div>
            </div>
          </div>
        </div>

        <!-- 报警事件列表 -->
        <div class="bg-white rounded-lg shadow-sm">
          <div class="p-4 border-b border-gray-100 flex justify-between items-center">
            <h2 class="font-bold text-gray-700">报警事件列表</h2>
            <button
              @click="exportToExcel"
              class="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 flex items-center !rounded-button whitespace-nowrap cursor-pointer">
              <i class="fas fa-download mr-2"></i>
              导出报表
            </button>
          </div>
          <div class="overflow-x-auto">
            <table class="w-full">
              <thead class="bg-gray-50">
                <tr>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">报警时间</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">报警级别</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">报警类型</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">报警位置</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">报警描述</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">处理状态</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">处理人</th>
                  <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                </tr>
              </thead>
              <tbody class="bg-white divide-y divide-gray-200">
                <tr v-for="(alarm, index) in paginatedAlarmList" :key="index" class="hover:bg-gray-50">
                  <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ alarm.time }}</td>
                  <td class="px-6 py-4 whitespace-nowrap">
                    <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full"
                      :class="alarm.levelClass">
                      {{ alarm.level }}
                    </span>
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ alarm.type }}</td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ alarm.location }}</td>
                  <td class="px-6 py-4 text-sm text-gray-900">{{ alarm.description }}</td>
                  <td class="px-6 py-4 whitespace-nowrap">
                    <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full"
                      :class="alarm.statusClass">
                      {{ alarm.status }}
                    </span>
                  </td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ alarm.handler }}</td>
                  <td class="px-6 py-4 whitespace-nowrap text-sm">
                    <button
                      @click="viewAlarmDetail(alarm)"
                      class="text-blue-600 hover:text-blue-800 mr-3 !rounded-button whitespace-nowrap cursor-pointer">
                      <i class="fas fa-eye mr-1"></i>
                      查看
                    </button>
                    <button v-if="alarm.status === '待处理'"
                      @click="handleAlarm(alarm)"
                      class="text-green-600 hover:text-green-800 !rounded-button whitespace-nowrap cursor-pointer">
                      <i class="fas fa-check-circle mr-1"></i>
                      处理
                    </button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
          <!-- 分页 -->
          <div class="px-6 py-4 flex items-center justify-between border-t border-gray-200">
            <div class="flex items-center">
              <span class="text-sm text-gray-700">每页显示</span>
              <select 
                v-model="pageSize" 
                @change="changePageSize(pageSize)"
                class="mx-2 border-gray-300 rounded text-sm !rounded-button cursor-pointer">
                <option v-for="size in pageSizeOptions" :key="size" :value="size">{{ size }}</option>
              </select>
              <span class="text-sm text-gray-700">条，共 {{ totalRecords }} 条</span>
            </div>
            <div class="flex items-center space-x-2" v-if="totalPages > 0">
              <button
                @click="prevPage"
                :disabled="currentPage === 1"
                class="px-3 py-1 border rounded text-sm disabled:opacity-50 disabled:cursor-not-allowed !rounded-button whitespace-nowrap cursor-pointer">
                上一页
              </button>
              
              <template v-for="page in pageNumbers" :key="page">
                <button
                  v-if="page !== '...'"
                  @click="goToPage(page)"
                  :class="[
                    'px-3 py-1 border rounded text-sm !rounded-button whitespace-nowrap cursor-pointer',
                    currentPage === page ? 'bg-blue-600 text-white' : 'hover:bg-gray-50'
                  ]">
                  {{ page }}
                </button>
                <span v-else class="text-sm">...</span>
              </template>
              
              <button
                @click="nextPage"
                :disabled="currentPage === totalPages"
                class="px-3 py-1 border rounded text-sm disabled:opacity-50 disabled:cursor-not-allowed !rounded-button whitespace-nowrap cursor-pointer">
                下一页
              </button>
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script>
import * as XLSX from 'xlsx';
import Header from "../components/Header.vue";
import { ElMessage, ElMessageBox } from 'element-plus'
export default {
  components: {
    Header
  },  
  data() {
    return {
      selectedTimeRange: 'month', // 默认选中本月
      // 搜索关键词
      searchKeyword: '',
      // 下拉框状态
      showLevelDropdown: false,
      showStatusDropdown: false,
      selectedLevel: '全部级别',
      selectedStatus: '全部状态',
      // 下拉框选项
      levelOptions: ['全部级别', '重大风险', '较大风险', '一般风险', '较小风险'],
      statusOptions: ['全部状态', '待处理', '处理中', '已处理'],
      originalAlarmList: [
        {
          time: '2025-10-09 10:23:45',
          level: '重大风险',
          levelClass: 'bg-red-100 text-red-800',
          type: '设备故障',
          location: '炼铁厂 - 3号高炉',
          description: '3号高炉煤气管道压力异常，可能存在泄漏风险',
          status: '待处理',
          statusClass: 'bg-yellow-100 text-yellow-800',
          handler: '-'
        },
        {
          time: '2025-10-09 09:15:32',
          level: '较大风险',
          levelClass: 'bg-orange-100 text-orange-800',
          type: '参数超限',
          location: '轧钢厂 - 2号轧钢机',
          description: '2号轧钢机轴承温度超过阈值，需要立即检查',
          status: '处理中',
          statusClass: 'bg-blue-100 text-blue-800',
          handler: '张工'
        },
        {
          time: '2025-10-08 08:47:12',
          level: '一般风险',
          levelClass: 'bg-yellow-100 text-yellow-800',
          type: '环境异常',
          location: '连铸车间 - 冷却水系统',
          description: '连铸机冷却水系统压力波动，需要关注',
          status: '已处理',
          statusClass: 'bg-green-100 text-green-800',
          handler: '李工'
        },
        {
          time: '2025-10-05 08:05:56',
          level: '较小风险',
          levelClass: 'bg-blue-100 text-blue-800',
          type: '设备预警',
          location: '烧结厂 - 除尘系统',
          description: '1号除尘器效率下降，建议安排维护检查',
          status: '已处理',
          statusClass: 'bg-green-100 text-green-800',
          handler: '王工'
        },
        {
          time: '2025-09-02 07:38:21',
          level: '较大风险',
          levelClass: 'bg-orange-100 text-orange-800',
          type: '通信异常',
          location: '动力厂 - 主变电站',
          description: '主变电站电压波动较大，可能影响设备稳定运行',
          status: '待处理',
          statusClass: 'bg-yellow-100 text-yellow-800',
          handler: '-'
        },
        {
          time: '2025-09-28 15:20:10',
          level: '重大风险',
          levelClass: 'bg-red-100 text-red-800',
          type: '安全隐患',
          location: '焦化厂 - 煤气净化',
          description: '煤气净化系统检测到有害气体浓度超标',
          status: '已处理',
          statusClass: 'bg-green-100 text-green-800',
          handler: '赵工'
        },
        {
          time: '2025-09-25 11:45:33',
          level: '一般风险',
          levelClass: 'bg-yellow-100 text-yellow-800',
          type: '设备异常',
          location: '热轧厂 - 加热炉',
          description: '3号加热炉温度控制异常，需要检查控制系统',
          status: '处理中',
          statusClass: 'bg-blue-100 text-blue-800',
          handler: '孙工'
        }
      ],
      alarmList: [],
      // 分页相关属性
      currentPage: 1,        // 当前页码
      pageSize: 10,          // 每页显示条数
      pageSizeOptions: [5, 10, 20], // 每页显示条数选项
      filteredAlarmList: []  // 筛选后的完整数据（用于分页）
    };
  },
  computed: {
    // 总页数
    totalPages() {
      return Math.ceil(this.filteredAlarmList.length / this.pageSize);
    },
    
    // 总记录数
    totalRecords() {
      return this.filteredAlarmList.length;
    },
    
    // 当前页的数据
    paginatedAlarmList() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.filteredAlarmList.slice(start, end);
    },
    
    // 分页按钮数组
    pageNumbers() {
      const pages = [];
      const total = this.totalPages;
      const current = this.currentPage;
      
      if (total <= 7) {
        // 如果总页数小于等于7，显示所有页码
        for (let i = 1; i <= total; i++) {
          pages.push(i);
        }
      } else {
        // 如果总页数大于7，显示省略号
        if (current <= 4) {
          // 当前页在前面
          for (let i = 1; i <= 5; i++) {
            pages.push(i);
          }
          pages.push('...');
          pages.push(total);
        } else if (current >= total - 3) {
          // 当前页在后面
          pages.push(1);
          pages.push('...');
          for (let i = total - 4; i <= total; i++) {
            pages.push(i);
          }
        } else {
          // 当前页在中间
          pages.push(1);
          pages.push('...');
          for (let i = current - 1; i <= current + 1; i++) {
            pages.push(i);
          }
          pages.push('...');
          pages.push(total);
        }
      }
      
      return pages;
    }
  },
  mounted() {
    // 初始化时设置filteredAlarmList
    this.filteredAlarmList = [...this.alarmList];
    // 初始化时显示本月数据
    this.filterByTimeRange('month');
  },
  methods: {
    // 切换报警级别下拉框显示状态
    toggleLevelDropdown() {
      this.showLevelDropdown = !this.showLevelDropdown;
      this.showStatusDropdown = false;
    },
    
    // 切换处理状态下拉框显示状态
    toggleStatusDropdown() {
      this.showStatusDropdown = !this.showStatusDropdown;
      this.showLevelDropdown = false;
    },
    
    // 选择报警级别
    selectLevel(level) {
      this.selectedLevel = level;
      this.showLevelDropdown = false;
      this.applyFilters();
    },
    
    // 选择处理状态
    selectStatus(status) {
      this.selectedStatus = status;
      this.showStatusDropdown = false;
      this.applyFilters();
    },
    
    // 应用所有筛选条件
    applyFilters() {
      let filteredData = [...this.originalAlarmList];
      
      // 按时间范围筛选
      const now = new Date();
      let startDate;
      
      switch (this.selectedTimeRange) {
        case 'today':
          startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());
          break;
        case 'week':
          const dayOfWeek = now.getDay();
          const daysToMonday = dayOfWeek === 0 ? 6 : dayOfWeek - 1;
          startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() - daysToMonday);
          break;
        case 'month':
          startDate = new Date(now.getFullYear(), now.getMonth(), 1);
          break;
        default:
          startDate = new Date(0);
      }
      
      filteredData = filteredData.filter(alarm => {
        const alarmDate = new Date(alarm.time);
        return alarmDate >= startDate && alarmDate <= now;
      });
      
      // 按报警级别筛选
      if (this.selectedLevel !== '全部级别') {
        filteredData = filteredData.filter(alarm => alarm.level === this.selectedLevel);
      }
      
      // 按处理状态筛选
      if (this.selectedStatus !== '全部状态') {
        filteredData = filteredData.filter(alarm => alarm.status === this.selectedStatus);
      }
      
      // 按搜索关键词筛选
      if (this.searchKeyword && this.searchKeyword.trim()) {
        const keyword = this.searchKeyword.trim().toLowerCase();
        filteredData = filteredData.filter(alarm => {
          return alarm.type.toLowerCase().includes(keyword) ||
                 alarm.location.toLowerCase().includes(keyword) ||
                 alarm.description.toLowerCase().includes(keyword) ||
                 alarm.level.toLowerCase().includes(keyword) ||
                 alarm.status.toLowerCase().includes(keyword) ||
                 alarm.handler.toLowerCase().includes(keyword);
        });
      }
      
      // 保存筛选后的完整数据
      this.filteredAlarmList = filteredData;
      
      // 重置到第一页
      this.currentPage = 1;
      
      
    },
    
    // 处理搜索输入
    handleSearch() {
      this.applyFilters();
    },
    
    filterByTimeRange(range) {
      this.selectedTimeRange = range;
      this.applyFilters();
    },
    
    // 分页相关方法
    // 跳转到指定页码
    goToPage(page) {
      if (page >= 1 && page <= this.totalPages) {
        this.currentPage = page;
      }
    },
    
    // 上一页
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
      }
    },
    
    // 下一页
    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
      }
    },
    
    // 改变每页显示条数
    changePageSize(newSize) {
      this.pageSize = parseInt(newSize);
      this.currentPage = 1; // 重置到第一页
    },
    
    // 导出Excel报表
    exportToExcel() {
      try {
        // 准备导出数据
        const exportData = this.alarmList.map((alarm, index) => ({
          '序号': index + 1,
          '报警时间': alarm.time,
          '报警级别': alarm.level,
          '报警类型': alarm.type,
          '报警位置': alarm.location,
          '报警描述': alarm.description,
          '处理状态': alarm.status,
          '处理人员': alarm.handler === '-' ? '未分配' : alarm.handler
        }));
        
        // 创建工作簿
        const wb = XLSX.utils.book_new();
        
        // 创建工作表
        const ws = XLSX.utils.json_to_sheet(exportData);
        
        // 设置列宽
        const colWidths = [
          { wch: 8 },   // 序号
          { wch: 20 },  // 报警时间
          { wch: 12 },  // 报警级别
          { wch: 12 },  // 报警类型
          { wch: 25 },  // 报警位置
          { wch: 40 },  // 报警描述
          { wch: 12 },  // 处理状态
          { wch: 12 }   // 处理人员
        ];
        ws['!cols'] = colWidths;
        
        // 添加工作表到工作簿
        XLSX.utils.book_append_sheet(wb, ws, '报警事件列表');
        
        // 生成文件名（包含当前时间）
        const now = new Date();
        const timestamp = now.getFullYear() + 
                         String(now.getMonth() + 1).padStart(2, '0') + 
                         String(now.getDate()).padStart(2, '0') + '_' +
                         String(now.getHours()).padStart(2, '0') + 
                         String(now.getMinutes()).padStart(2, '0');
        const filename = `报警事件报表_${timestamp}.xlsx`;
        
        // 导出文件
        XLSX.writeFile(wb, filename);
        
        // 显示成功消息
        ElMessage.success(`导出成功！共导出 ${exportData.length} 条记录`);
        
      } catch (error) {
        ElMessage.error('导出失败，请重试');
      }
    },
    
    // 查看报警详情
    viewAlarmDetail(alarm) {
      // 构建详情信息
      const detailInfo = `
报警详情信息：

报警时间：${alarm.time}
报警级别：${alarm.level}
报警类型：${alarm.type}
报警位置：${alarm.location}
报警描述：${alarm.description}
处理状态：${alarm.status}
处理人员：${alarm.handler === '-' ? '未分配' : alarm.handler}
      `;
      
      // 显示详情弹窗
      ElMessage.success(detailInfo);
      
    },
    
    // 处理报警事件
    handleAlarm(alarm) {
      // 确认处理操作
      const confirmed = ElMessageBox.confirm(
  `报警类型：${alarm.type}\n报警位置：${alarm.location}`,
  '确定要处理这个报警事件吗？',
  {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }
)
      
      if (confirmed) {
        // 更新报警状态
        const alarmIndex = this.originalAlarmList.findIndex(item => 
          item.time === alarm.time && 
          item.location === alarm.location && 
          item.description === alarm.description
        );
        
        if (alarmIndex !== -1) {
          // 更新原始数据
          this.originalAlarmList[alarmIndex].status = '处理中';
          this.originalAlarmList[alarmIndex].statusClass = 'bg-blue-100 text-blue-800';
          this.originalAlarmList[alarmIndex].handler = '当前用户'; // 这里可以替换为实际登录用户
          
          // 重新应用筛选
          this.applyFilters();
          
          // 显示成功消息
          ElMessage.success('报警事件已开始处理！');
        }
      }
    }
  }
};
</script>

<style scoped>
.table-row-hover:hover {
  background-color: rgba(243, 244, 246, 0.5);
}
</style>
